const Position = require('../models/Position');
const { parseFilesByParams } = require('../utils/fileParser');

// 存储职位数据到 MongoDB
async function storePositionData(province, city, date) {
  try {
    // 解析 Excel 文件
    const result = await parseFilesByParams(province, city, date);
    
    if (!result.data || result.data.length === 0) {
      console.log('没有找到职位数据');
      return { success: false, message: '没有找到职位数据' };
    }
    
    // 批量插入数据到 MongoDB
    const operations = result.data.map(position => ({
      updateOne: {
        filter: { 
          positionCode: position.positionCode,
          province: result.province,
          city: result.city,
          date: result.date
        },
        update: {
          $set: {
            ...position,
            province: result.province,
            city: result.city,
            date: result.date,
            updatedAt: new Date()
          }
        },
        upsert: true
      }
    }));
    
    const bulkWriteResult = await Position.bulkWrite(operations);
    
    console.log(`成功存储职位数据: ${bulkWriteResult.upsertedCount} 条新增, ${bulkWriteResult.modifiedCount} 条更新`);
    
    return { 
      success: true, 
      insertedCount: bulkWriteResult.upsertedCount,
      modifiedCount: bulkWriteResult.modifiedCount,
      data: result.data
    };
  } catch (error) {
    console.error('存储职位数据失败:', error);
    throw error;
  }
}

// 查询职位数据
async function queryPositions(province, city, date, filters = {}) {
  try {
    // 构建查询条件
    const query = { province, city, date, ...filters };
    
    // 执行查询
    const positions = await Position.find(query).sort({ positionCode: 1 });
    
    return {
      success: true,
      count: positions.length,
      data: positions
    };
  } catch (error) {
    console.error('查询职位数据失败:', error);
    throw error;
  }
}

// 删除职位数据
async function deletePositionData(province, city, date, positionCode = null) {
  try {
    const query = { province, city, date };
    if (positionCode) {
      query.positionCode = positionCode;
    }
    
    const result = await Position.deleteMany(query);
    
    return {
      success: true,
      deletedCount: result.deletedCount
    };
  } catch (error) {
    console.error('删除职位数据失败:', error);
    throw error;
  }
}

module.exports = {
  storePositionData,
  queryPositions,
  deletePositionData
};